package com.kehutong.contact.service.impl;

import com.kehutong.common.util.Token;
import com.kehutong.contact.entity.Contact;
import com.kehutong.contact.entity.ContactComment;
import com.kehutong.contact.entity.ContactDynamics;
import com.kehutong.contact.entity.Customer;
import com.kehutong.contact.enums.CustomerStatus;
import com.kehutong.contact.enums.FollowUpType;
import com.kehutong.contact.enums.FollowUpWay;
import com.kehutong.contact.service.ContactDynamicsService;
import com.kehutong.contact.util.DateUtil;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.orm.util.Enums;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author liujinwang
 * description:
 */
@WebService("/crm/contact/dynamics/service")
public class ContactDynamicsServiceImpl implements ContactDynamicsService {

    private static final Logger logger = LoggerFactory.getLogger(ContactDynamicsServiceImpl.class);

    @Inject
    private JdbcSession jdbcSession;

    @Override
    public Page<ContactDynamics> page(JSONObject jsonObject) {
        String type = jsonObject.getString("type");
        FindPage<ContactDynamics> find = jdbcSession.findPage(ContactDynamics.class)
                .eq(jsonObject, "contactId")
                .eq("deleted", false);
                if (Objects.nonNull(type)) {
                    find.eq("type", type);
                }
                return find.order("createTime", "desc").page(jsonObject).exe();
    }

    @Override
    public Object list(JSONObject jsonObject) {
        return jdbcSession.findArray(ContactDynamics.class)
                .eq(jsonObject,  "contactId")
                .eq("deleted",false)
                .order("createTime", "desc")
                .exe();
    }

    @Override
    public Object save(Token token, JSONObject jsonObject) throws Exception {
        ContactDynamics contactDynamics = Pool.newInstance(ContactDynamics.class);
        buildContactDynamics(jsonObject,contactDynamics);
        contactDynamics.setFollowUpId(token.getUuid());
        contactDynamics.setFollowUpName(token.getUsername());
        jdbcSession.insert(contactDynamics);
        extracted(contactDynamics);
        return Result.success(contactDynamics);
    }

    private void buildContactDynamics(JSONObject jsonObject, ContactDynamics contactDynamics) {
        String contactId = jsonObject.getString("contactId");
        Contact contact = Pool.get(Contact.class, contactId);
        if (Objects.isNull(contact)) {
            throw new RuntimeException("联系人不存在");
        }
        contactDynamics.setCustomerId(jsonObject.getString("customerId"));
        contactDynamics.setType(Enums.getEnum(FollowUpType.class, jsonObject.getJSONObject("type").getString("id")));
        contactDynamics.setFollowUpWay(Enums.getEnum(FollowUpWay.class, jsonObject.getJSONObject("followUpWay").getString("id")));
        contactDynamics.setFollowUpTime(LocalDateTime.parse(jsonObject.getString("followUpTime"),DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        contactDynamics.setDesc(jsonObject.getString("desc"));
        contactDynamics.setCorpFullName(jsonObject.getString("corpFullName"));
        contactDynamics.setCustomerStatus(Enums.getEnum(CustomerStatus.class, jsonObject.getJSONObject("customerStatus").getString("id")));
        contactDynamics.setContactName(jsonObject.getString("contactName"));
        contactDynamics.setContactId(jsonObject.getString("contactId"));
        contactDynamics.setFileName(jsonObject.getString("fileName"));
        contactDynamics.setFileId(jsonObject.getString("fileId"));
    }

    @Override
    public Object update(ContactDynamics contactDynamics) throws Exception{
        jdbcSession.updateById(contactDynamics);
        extracted(contactDynamics);
        return Result.success(contactDynamics);
    }

    private void extracted(ContactDynamics contactDynamics) {
        Customer customer = Pool.get(Customer.class, contactDynamics.getCustomerId());
        if (Objects.nonNull(customer)) {
            customer.setCustomerStatus(contactDynamics.getCustomerStatus());
            customer.setLastFollowUpTime(contactDynamics.getFollowUpTime());
            customer.setFollowUpId(contactDynamics.getFollowUpId());
            customer.setFollowUpName(contactDynamics.getFollowUpName());
            jdbcSession.updateById(customer);
        }
    }

    @Override
    public Object delete(ContactDynamics contactDynamics) throws Exception{
        contactDynamics = Pool.get(ContactDynamics.class, contactDynamics.getId());
        if (Objects.nonNull(contactDynamics)) {
            contactDynamics.setDeleted(true);
            jdbcSession.updateById(contactDynamics);
            List<ContactComment> commentList = jdbcSession.findArray(ContactComment.class).eq("contactDynamicsId", contactDynamics.getId()).exe();
            if (Objects.nonNull(commentList)) {
                jdbcSession.deleteById(commentList);
            }
        }
        return Result.success();
    }

}
